<template>
  <div class="box">
    <div class="boxnav mapc" style="height: 550px; position: relative">
      <div class="map" id="map" style="width: 100%; height: 100%; position: relative;">
        <!-- 取消动态光边与扫描线效果 -->
        <!-- <div class="map-glow-border"></div>
        <div class="map-scan-line"></div> -->
        <object 
          :data="mapSvgPath" 
          type="image/svg+xml" 
          id="mapImage" 
          style="pointer-events: auto;"
          @load="onMapLoad"
        >
          东莞地图
        </object>
        
        <!-- 图例 -->
        <div class="map-legend" id="mapLegend">
          <div class="legend-toggle" @click="toggleLegend">
            <span class="legend-title">支行评分等级</span>
            <span class="legend-arrow" :class="{ rotated: legendCollapsed }">▼</span>
          </div>
          <div class="legend-content" :class="{ collapsed: legendCollapsed }">
            <div class="legend-item">
              <div class="legend-color" style="background: #29D9D5;"></div>
              <span>优秀 (90分以上)</span>
            </div>
            <div class="legend-item">
              <div class="legend-color" style="background: #3C8BFF;"></div>
              <span>良好 (85-89分)</span>
            </div>
            <div class="legend-item">
              <div class="legend-color" style="background: #4A5DDE;"></div>
              <span>中等 (80-84分)</span>
            </div>
            <div class="legend-item">
              <div class="legend-color" style="background: #5A3EC8;"></div>
              <span>预警 (75-79分)</span>
            </div>
            <div class="legend-item">
              <div class="legend-color" style="background: #4C3087;"></div>
              <span>待改进 (75分以下)</span>
            </div>
          </div>
        </div>
        
        <!-- 悬停提示框 -->
        <div 
          v-show="tooltip.visible" 
          class="map-tooltip" 
          :style="{ left: tooltip.x + 'px', top: tooltip.y + 'px' }"
        >
          <div class="tooltip-header" :style="{ background: tooltip.color }">
            <div class="tooltip-title">{{ tooltip.branchName }}</div>
            <div class="tooltip-level">{{ tooltip.level }}</div>
          </div>
          <div class="tooltip-body">
            <div class="tooltip-row">
              <span class="tooltip-label">综合得分：</span>
              <span class="tooltip-value highlight">{{ tooltip.score }}分</span>
            </div>
            <div class="tooltip-row">
              <span class="tooltip-label">全行排名：</span>
              <span class="tooltip-value">第 {{ tooltip.rank }} 名</span>
            </div>
            <div class="tooltip-row">
              <span class="tooltip-label">加权总分：</span>
              <span class="tooltip-value">{{ tooltip.weightedScore }}</span>
            </div>
          </div>
        </div>
        
        <!-- 底部中间按钮 -->
        <div class="detail-button-container">
          <button 
            class="detail-button" 
            @click="showDetailDialog = true"
            :disabled="isLoading || Object.keys(branchScores).length === 0"
          >
            <span class="button-icon">📊</span>
            <span class="button-text">
              {{ isLoading ? '加载中...' : '查看详细评分' }}
            </span>
            <span v-if="!isLoading" class="button-arrow">→</span>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 综合评分详细对话框 -->
    <div v-if="showDetailDialog" class="dialog-overlay" @click="showDetailDialog = false">
      <div class="dialog-container" @click.stop>
        <div class="dialog-header">
          <h2>综合评分详细</h2>
          <button class="dialog-close" @click="showDetailDialog = false">✕</button>
        </div>
        <div class="dialog-body">
          <ScoreDetailPage 
            v-if="sharedScoreData"
            :sharedData="sharedScoreData"
          />
        </div>
      </div>
    </div>
    
    <!-- 支行详情对话框 -->
    <div v-if="showBranchDialog" class="dialog-overlay branch-detail-overlay" @click="showBranchDialog = false">
      <div class="dialog-container branch-detail-container" @click.stop>
        <div class="dialog-header">
          <h2>{{ selectedBranch?.orgName }} - 业务维度详情</h2>
          <button class="dialog-close" @click="showBranchDialog = false">✕</button>
        </div>
        <div class="dialog-body branch-dialog-body">
          <BranchDetailPage 
            v-if="selectedBranch"
            :orgNo="selectedBranch.orgNo"
            :branchName="selectedBranch.orgName"
            @close="showBranchDialog = false"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useBranchScore } from '../composables/useBranchScore.js'
import { useBranchScoreStore } from '../stores/branchScoreStore.js'
import { saveBranchScores } from '../utils/scoreDB.js'
import ScoreDetailPage from './ScoreDetailPage.vue'
import BranchDetailPage from './BranchDetailPage.vue'

const legendCollapsed = ref(false)
const showDetailDialog = ref(false)
const sharedScoreData = ref(null)

// 支行详情对话框状态
const showBranchDialog = ref(false)
const selectedBranch = ref(null)

// Tooltip 状态
const tooltip = ref({
  visible: false,
  x: 0,
  y: 0,
  branchName: '',
  score: 0,
  rank: 0,
  weightedScore: 0,
  level: '',
  color: ''
})

// 根据环境动态设置地图SVG路径
const mapSvgPath = computed(() => {
  if (import.meta.env.PROD) {
    // 生产环境使用完整路径前缀
    return '/coolv/vfs/root/products/ebi/sys/coolrpt/coolresource/images/map.svg'
  } else {
    // 开发环境使用简单路径
    return '/images/map.svg'
  }
})

// 使用综合评分组件
const { 
  isLoading, 
  branchScores, 
  fetchBranchScores, 
  getBranchScore,
  getScoreLevel,
  getScoreColor 
} = useBranchScore()

// 使用评分存储
const branchScoreStore = useBranchScoreStore()

// 地图变换状态
const mapTransform = ref({
  zoom: 0.9,
  x: 0,
  y: 0
})

const isDragging = ref(false)
const dragStart = ref({ x: 0, y: 0, transformX: 0, transformY: 0 })

// 图例切换
const toggleLegend = () => {
  legendCollapsed.value = !legendCollapsed.value
}

// 地图加载完成后的处理
const onMapLoad = () => {
  setTimeout(() => {
    initMapColoring()
    initMapInteraction()
  }, 1000)
}

// 初始化地图着色
const initMapColoring = () => {
  const svgObject = document.getElementById('mapImage')
  if (!svgObject || !svgObject.contentDocument) return
  
  const svgDoc = svgObject.contentDocument
  const paths = svgDoc.querySelectorAll('.zhenqu')
  
  paths.forEach(path => {
    const areaName = path.id // 区域名称（如"南城"、"东城"）
    
    // 根据区域名称查找对应的支行评分
    const branchScore = Object.values(branchScores.value).find(branch => 
      branch.orgName && branch.orgName.includes(areaName)
    )
    
    if (branchScore) {
      const score = branchScore.score
      const color = getScoreColor(score)
      const colorWithAlpha = color.replace(')', ', 0.8)').replace('rgb', 'rgba')
      
      path.style.fill = colorWithAlpha
      path.style.cursor = 'pointer'
      
      // 添加交互事件
      path.addEventListener('mouseover', (e) => {
        path.style.fill = "rgba(200, 200, 200, 0.7)"
        showTooltip(e, branchScore)
      })
      
      path.addEventListener('mouseout', () => {
        path.style.fill = colorWithAlpha
        hideTooltip()
      })
      
      path.addEventListener('mousemove', (e) => {
        updateTooltipPosition(e)
      })
      
      path.addEventListener('click', () => {
        // 打开支行详情对话框
        selectedBranch.value = {
          orgNo: branchScore.orgNo,
          orgName: branchScore.orgName
        }
        showBranchDialog.value = true
        hideTooltip()
        console.log(`点击了${branchScore.orgName}，分数: ${score}分，排名: ${branchScore.rank}`)
      })
    }
  })
}

// 显示 Tooltip
const showTooltip = (event, branchScore) => {
  const score = branchScore.score
  tooltip.value = {
    visible: true,
    x: event.pageX + 15,
    y: event.pageY + 15,
    branchName: branchScore.orgName,
    score: score,
    rank: branchScore.rank,
    weightedScore: branchScore.weightedScore.toFixed(2),
    level: getScoreLevel(score),
    color: getScoreColor(score)
  }
}

// 隐藏 Tooltip
const hideTooltip = () => {
  tooltip.value.visible = false
}

// 更新 Tooltip 位置
const updateTooltipPosition = (event) => {
  if (tooltip.value.visible) {
    tooltip.value.x = event.pageX + 15
    tooltip.value.y = event.pageY + 15
  }
}

// 初始化地图交互
const initMapInteraction = () => {
  const mapImage = document.getElementById('mapImage')
  const mapContainer = document.getElementById('map')
  
  if (!mapImage || !mapContainer) return
  
  // 鼠标拖拽 - 已禁用
  // mapImage.addEventListener('mousedown', (e) => {
  //   isDragging.value = true
  //   dragStart.value = {
  //     x: e.clientX,
  //     y: e.clientY,
  //     transformX: mapTransform.value.x,
  //     transformY: mapTransform.value.y
  //   }
  //   e.preventDefault()
  // })
  
  // document.addEventListener('mousemove', (e) => {
  //   if (isDragging.value) {
  //     const deltaX = e.clientX - dragStart.value.x
  //     const deltaY = e.clientY - dragStart.value.y
  //     mapTransform.value.x = dragStart.value.transformX + deltaX
  //     mapTransform.value.y = dragStart.value.transformY + deltaY
  //     updateMapTransform()
  //   }
  // })
  
  // document.addEventListener('mouseup', () => {
  //   isDragging.value = false
  // })
  
  // 鼠标滚轮缩放 - 已禁用
  // mapContainer.addEventListener('wheel', (e) => {
  //   e.preventDefault()
  //   if (e.deltaY < 0) {
  //     zoomIn()
  //   } else {
  //     zoomOut()
  //   }
  // })
}

// 缩放函数
const zoomIn = () => {
  if (mapTransform.value.zoom < 3) {
    mapTransform.value.zoom += 0.2
    updateMapTransform()
  }
}

const zoomOut = () => {
  if (mapTransform.value.zoom > 0.5) {
    mapTransform.value.zoom -= 0.2
    updateMapTransform()
  }
}

const resetZoom = () => {
  mapTransform.value = { zoom: 0.9, x: 0, y: 0 }
  updateMapTransform()
}

const updateMapTransform = () => {
  const mapImage = document.getElementById('mapImage')
  if (mapImage) {
    mapImage.style.transform = `translate(calc(-50% + ${mapTransform.value.x}px), calc(-50% + ${mapTransform.value.y}px)) scale(${mapTransform.value.zoom})`
  }
}

onMounted(async () => {
  console.log('[地图组件] 开始加载支行评分数据...')
  
  // 先加载评分数据
  try {
    // 动态获取系统当前日期
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const currentDate = `${year}${month}${day}`
    
    console.log('[地图组件] 使用系统日期:', currentDate)
    await fetchBranchScores(currentDate)
    console.log('[地图组件] 评分数据加载完成，共', Object.keys(branchScores.value).length, '个支行')
    
    // 将评分数据转换为简单格式后保存到全局store
    // 从 { orgNo: { score, rank, ... } } 转换为 { orgNo: score }
    console.log('[地图组件] 开始转换评分数据格式')
    console.log('[地图组件] 原始数据示例:', Object.entries(branchScores.value).slice(0, 2))
    
    const scoresMap = {}
    Object.entries(branchScores.value).forEach(([orgNo, data]) => {
      if (!data) return
      let val = null
      if (typeof data.finalScore === 'number') val = data.finalScore
      else if (typeof data.score === 'number') val = data.score
      else if (typeof data.finalScore === 'string' && data.finalScore.trim() !== '') val = parseFloat(data.finalScore)
      else if (typeof data.score === 'string' && data.score.trim() !== '') val = parseFloat(data.score)
      if (Number.isFinite(val)) {
        scoresMap[orgNo] = val
      }
    })
    
    console.log('[地图组件] 转换后数据示例:', Object.entries(scoresMap).slice(0, 3))
    console.log('[地图组件] 准备保存到store...')
    
    // 写入store（内存）
    try {
      // 保存简化的评分数据
      branchScoreStore.setScores(scoresMap)
      
      // 保存原始数据（分子分母和指标数据）到 store
      if (window.__RAW_SCORE_DATA__) {
        branchScoreStore.setRawData({
          scoreData: window.__RAW_SCORE_DATA__.scoreData,
          scoreResult: window.__RAW_SCORE_DATA__.scoreResult,
          indicators: window.__RAW_SCORE_DATA__.indicators,
          bussDate: window.__RAW_SCORE_DATA__.bussDate,
          startDate: window.__RAW_SCORE_DATA__.startDate
        })
        console.log('[地图组件] 原始评分数据（分子分母、指标）已保存到 store')
      }
      
      // 保存评分到 IndexedDB
      await saveBranchScores(scoresMap)
      console.log('[地图组件] 评分数据已保存：store 与 IndexedDB。数量', Object.keys(scoresMap).length)
    } catch (e) {
      console.warn('[地图组件] 保存评分到IndexedDB失败，将继续使用内存store。', e)
    }
    
    // 准备共享数据（从全局变量读取，供对话框使用）
    if (window.__RAW_SCORE_DATA__) {
      sharedScoreData.value = {
        scoreData: window.__RAW_SCORE_DATA__.scoreData,
        scoreResult: window.__RAW_SCORE_DATA__.scoreResult,
        indicators: window.__RAW_SCORE_DATA__.indicators,
        bussDate: window.__RAW_SCORE_DATA__.bussDate
      }
      console.log('[地图组件] 共享数据已准备好（供对话框使用）')
    }
  } catch (err) {
    console.error('[地图组件] 评分数据加载失败:', err)
  }
  
  // 延迟初始化以确保SVG加载完成
  setTimeout(() => {
    const svgObject = document.getElementById('mapImage')
    if (svgObject && svgObject.contentDocument) {
      initMapColoring()
      initMapInteraction()
    } else if (svgObject) {
      svgObject.addEventListener('load', onMapLoad)
    }
  }, 2000)
})

// 监听 branchScores 变化，更新共享数据
import { watch } from 'vue'
watch(() => window.__RAW_SCORE_DATA__, (newVal) => {
  if (newVal) {
    sharedScoreData.value = {
      scoreData: newVal.scoreData,
      scoreResult: newVal.scoreResult,
      indicators: newVal.indicators,
      bussDate: newVal.bussDate
    }
    console.log('[地图组件] 共享数据已更新')
  }
}, { deep: true })
</script>

<style scoped>
.legend-arrow.rotated {
  transform: rotate(-90deg);
}

.legend-content.collapsed {
  max-height: 0;
  overflow: hidden;
}

/* Tooltip 样式 */
.map-tooltip {
  position: fixed;
  z-index: 9999;
  pointer-events: none;
  min-width: 200px;
  background: rgba(20, 30, 50, 0.95);
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
  overflow: hidden;
  animation: tooltipFadeIn 0.2s ease-out;
}

@keyframes tooltipFadeIn {
  from {
    opacity: 0;
    transform: translateY(-5px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.tooltip-header {
  padding: 12px 16px;
  background: linear-gradient(135deg, #29D9D5 0%, #3C8BFF 100%);
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.tooltip-title {
  font-size: 16px;
  font-weight: bold;
  color: #ffffff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.tooltip-level {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.9);
  background: rgba(255, 255, 255, 0.2);
  padding: 2px 8px;
  border-radius: 12px;
  font-weight: 500;
}

.tooltip-body {
  padding: 12px 16px;
  background: rgba(20, 30, 50, 0.95);
}

.tooltip-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

.tooltip-row:last-child {
  border-bottom: none;
}

.tooltip-label {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.7);
}

.tooltip-value {
  font-size: 14px;
  font-weight: 500;
  color: #ffffff;
}

.tooltip-value.highlight {
  font-size: 18px;
  font-weight: bold;
  color: #29D9D5;
  text-shadow: 0 0 10px rgba(41, 217, 213, 0.5);
}

/* 底部按钮容器 */
.detail-button-container {
  position: absolute;
  bottom: 15px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
}

/* 详细评分按钮 */
.detail-button {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 18px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 20px;
  color: white;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  box-shadow: 0 3px 12px rgba(102, 126, 234, 0.35);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  opacity: 0.92;
}

.detail-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.5s ease;
}

.detail-button:hover::before {
  left: 100%;
}

.detail-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.5);
  opacity: 1;
}

.detail-button:active {
  transform: translateY(0);
}

.detail-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  pointer-events: none;
}

.button-icon { font-size: 16px; }

/* 取消按钮图标跳动动画 */

.button-text {
  letter-spacing: 0.3px;
}

.button-arrow {
  font-size: 14px;
  transition: transform 0.3s ease;
}

.detail-button:hover .button-arrow {
  transform: translateX(3px);
}

/* 对话框遮罩层 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 对话框容器 */
.dialog-container {
  background: white;
  border-radius: 12px;
  width: 95vw;
  max-width: 1800px;
  height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  animation: slideUp 0.3s ease;
  overflow: hidden;
}

/* 支行详情对话框容器 */
.branch-detail-container {
  max-width: 1600px;
  height: 95vh;
}

.branch-dialog-body {
  padding: 0 !important;
  overflow-y: auto;
}

.branch-dialog-body .page-header-info {
  display: none;
}

@keyframes slideUp {
  from {
    transform: translateY(50px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

/* 对话框头部 */
.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.dialog-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

/* 关闭按钮 */
.dialog-close {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  color: white;
  font-size: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.dialog-close:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: rotate(90deg);
}

/* 对话框内容区 */
.dialog-body {
  flex: 1;
  overflow: hidden;
  padding: 0;
  background: #f5f5f5;
}

/* 对话框内容样式 */
.dialog-body {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  background: #f5f7fa;
}

/* 对话框内组件样式强制重置 */
.dialog-body :deep(*) {
  box-sizing: border-box;
}

/* 清除可能的全局样式干扰 */
.dialog-body :deep(.abnormal-item) {
  all: unset;
  display: flex !important;
  align-items: center !important;
  gap: 10px !important;
  padding: 10px 12px !important;
  background: #3b3e7e !important;
  border: 1px solid #4d508f !important;
  border-radius: 8px !important;
  font-size: 13px !important;
  color: inherit !important; /* 交由子组件自身配色控制，避免强制覆盖导致对比不足 */
  box-sizing: border-box !important;
}

.dialog-body :deep(.abnormal-item .indicator-name) {
  font-weight: 700 !important;
  color: #253b8a !important;
  background: #c7d2fe !important;
  padding: 4px 10px !important;
  border-radius: 14px !important;
}

.dialog-body :deep(.abnormal-item .indicator-value) {
  color: #e4e7ff !important;
  font-weight: 600 !important;
}

.dialog-body :deep(.abnormal-item .indicator-zscore) {
  font-weight: 700 !important;
  padding: 4px 10px !important;
  border-radius: 4px !important;
  font-family: monospace !important;
}

.dialog-body :deep(.abnormal-item .indicator-zscore.zscore-high) {
  background: #f8d7da !important;
  color: #842029 !important;
  border: 1px solid #f1aeb5 !important;
}

.dialog-body :deep(.abnormal-item .indicator-zscore.zscore-low) {
  background: #d1e7dd !important;
  color: #0f5132 !important;
  border: 1px solid #a3cfbb !important;
}

.dialog-body :deep(.abnormal-item .indicator-score) {
  color: #664d03 !important;
  font-size: 12px !important;
  font-weight: 700 !important;
  background: #fff3cd !important;
  padding: 4px 10px !important;
  border-radius: 14px !important;
  border: 1px solid #ffe69c !important;
}

/* 滚动条样式 */
.dialog-body::-webkit-scrollbar {
  width: 10px;
}

.dialog-body::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.dialog-body::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 5px;
}

.dialog-body::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style>
